﻿using Castle.MicroKernel.Registration;
using System.Web.Mvc;
using Castle.MicroKernel;
using Inovout.Web.Controllers;
using Inovout.Web.Binders;
using System.Reflection;
using System.IO;
using System.Linq;

namespace Inovout.Web
{
    public class WebComponentRegistrar : ComponentRegistrar
    {
        public override void Register()
        {
            Container.Register(Component.For<IControllerFactory>().ImplementedBy<ControllerFactory>()
                              , Component.For<IModelBinder>().ImplementedBy<EntityModelBinder>().LifeStyle.Transient
           );
        }

        public override void Register(Assembly assembly)
        {
            //Property.ForKey
            Container.Register(AllTypes
                                       .FromAssembly(assembly)
                                       .BasedOn<IController>()
                                       .Configure(c => c.LifeStyle.Transient
                                                        .Named(c.Implementation.Name.ToLower())
                                                        .OnCreate(BuildController)));
            //处理js,css.aspx,cshtml,vbhtml
            foreach (string webResourceFileName in
                   assembly.GetManifestResourceNames().Where(fileName =>
                        webResourceFileExtensions.Contains(fileName.Substring(fileName.LastIndexOf(".")).ToLower())))
            {
                FileInfo fileInfo = new FileInfo(Application.Path + webResourceFileName);
                if (!fileInfo.Exists)
                {
                    using (FileStream fileStream = fileInfo.OpenRead())
                    {
                        assembly.GetManifestResourceStream(webResourceFileName).CopyTo(fileStream);
                    }
                }
            }
        }
        private readonly string[] webResourceFileExtensions = new string[] { "js", "css", "aspx", "cshtml", "vbshtml" };
        private void BuildController(IKernel kernel, object instance)
        {
            BaseController controller = instance as BaseController;
            if (controller.Logger == null)
            {
                //controller.Logger = Logger.Create(controller.GetType());
            }

        }
    }
}
